#include <stdio.h>

#include <ruby.h>

#if defined(__APPLE_CC__)
  #include <SDL/SDL.h>

  #include <OpenAL/al.h>
  #include <OpenAL/alc.h>
#elif defined(WIN32)
  #include <SDL/SDL.h>

  #include <AL/al.h>
  #include <AL/alc.h>
#else
  #include <SDL.h>

  #include <AL/al.h>
  #include <AL/alc.h>
#endif

#include "AS.h"

ALCdevice *AL_device;
ALCcontext *AL_context;

static VALUE load_init_dot_rb(VALUE unused)
{
	//Initialize the Aerosol module.
	rbas_mAS = rb_define_module("AS");
	
	//Evaluate init.rb if it exists.
	rb_eval_string("puts \"Starting Aerosol in #{Dir.pwd}\"");
	rb_eval_string("load 'init.rb' if File.exist? 'init.rb'");
	
	//Define AS::GAME_MAIN and AS::LIB_DIR if they are undefined. This will run the code inside the bundle.
	rb_eval_string("AS::LIB_DIR = File.expand_path 'Aerosol' unless defined? AS::LIB_DIR");
	
	//Add the Aerosol directory to the search path
	rb_eval_string("$: << AS::LIB_DIR");
		
	return Qnil; //need to return something.
}

static void initialize_SDL(void)
{
	Uint32 initflags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK |SDL_INIT_TIMER;
	
	//Initialize the SDL library
	if ( SDL_Init(initflags) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}
}

static void initialize_AL(void)
{
	AL_device = alcOpenDevice(NULL);
	AL_context = alcCreateContext(AL_device, NULL);
	alcMakeContextCurrent(AL_context);
}	

void AS_init(void)
{
	initialize_SDL();
	initialize_AL();

	int err = 0;
	rb_protect(load_init_dot_rb, 0, &err);
	if(err) AS_printException("Exception during initializiation. Check init.rb for errors.");
}
